﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace FlightSearchServer
{
    public class FlightSearchHost
    {
        private const int NUMBER_OF_ARGUMENTS = 2;

        private const int CLIENT_PORT_INDEX = 0;

        private const int SERVER_PORT_INDEX = 1;

        static public void Main(string[] args)
        {
            print console = Console.WriteLine;

            if (args.Length != NUMBER_OF_ARGUMENTS)
            {
                console( "Incorrect input format");
                console( "Expected format: <client port> <server port>");
                return;
            }

            try
            {
                Convert.ToInt32(args[CLIENT_PORT_INDEX]);
            }
            catch ( InvalidCastException e)
            {
                console( "Invalid number format of client port.");
                return;
            }

            try
            {
                Convert.ToInt32(args[SERVER_PORT_INDEX]);
            }
            catch (InvalidCastException e)
            {
                console("Invalid number format of server port.");
                return;
            }
            console("About to start flight search server.");
            console("Press any key while you be ready.");
            Console.ReadLine();
            using (ServiceHost host = new ServiceHost( typeof(FlightSearchService), 
                               new Uri( String.Format( "http://localhost:{0}/SearchServices", args[SERVER_PORT_INDEX]))),
                    registHost = new ServiceHost( typeof(VendorRegistration), 
                               new Uri( String.Format( "http://localhost:{0}/VendorServices", args[SERVER_PORT_INDEX])))) {
                try
                {
                    console("Endpoints for flight search services");
                    foreach (ServiceEndpoint endpoint in host.Description.Endpoints)
                    {
                        Console.WriteLine("Endpoint ({0}) listening at uri: {1}", endpoint.Name, endpoint.ListenUri);
                    }
                    host.Open();
                    console("");
                    console("Endpoints for ticket sellers vendors services.");
                    foreach (ServiceEndpoint endpoint in registHost.Description.Endpoints)
                    {
                        console("Endpoint ({0}) listening at uri: {1}", endpoint.Name, endpoint.ListenUri);
                    }
                    registHost.Open();
                    console( "Press any key to stop server from running.");
                    Console.ReadLine();
                } finally {
                    host.Close( );
                    registHost.Close();
                }
            }
            Console.ReadLine();
        }
    }
}